# -*- coding: utf-8 -*-
#coding=utf-8

import web
import os
import config
from action.admin.base import adminAction
from model.news import news
from model.category import category
from model.album import album
from model.image import image

'''
Admin controller: producing news administration views.
'''
class refererAction(adminAction):
    def __init__(self, name = '资讯管理'):
        adminAction.__init__(self, name)


    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'delete':
            return self.delete()
        elif name == 'add':
            return self.add()
        elif name == 'edit':
            return self.edit()
        elif name == 'listForBatchDel':
            return self.listForBatchDel()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'modify':
            return self.modify()
        elif name == 'deleteBatch':
            return self.deleteBatch()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        newsObj = news()
        listData = newsObj.getOne('COUNT(*) AS `total`', condition)
        totalCount = listData['total']
        newsList = newsObj.getList('*', condition, 'id desc', str(offset) + ',' + str(count))

        pageString = self.getPageStr(self.makeUrl('/admin/news/list'), page, count, totalCount)
        self.privData['NEWS_LIST'] = newsList
        self.privData['PAGE_STRING'] = pageString

        categoryList = category().getList('*', condition)
        self.privData['CATEGORY_LIST'] = {}
        for i in categoryList:    
            self.privData['CATEGORY_LIST'][i['id']] = i['name']
        return self.display('newsList')

    def listForBatchDel(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        newsObj = news()
        listData = newsObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        newsList = newsObj.getList('*', condition, 'id asc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/admin/news/list', page, count, totalCount)
        self.privData['NEWS_LIST'] = newsList
        self.privData['PAGE_STRING'] = pageString

        categoryList = category().getList('*', condition)
        self.privData['CATEGORY_LIST'] = {}
        for i in categoryList:    
            self.privData['CATEGORY_LIST'][i['id']] = i['name']

        return self.display('newsBatchDel')

    def delete(self):
        inputParams = self.getInput()

        try:
            condition = {'id': int(inputParams['id'])}
            news().delete(condition)
        except Exception, e:
            return self.error(msg='资讯删除失败: %s' % e, url=self.makeUrl('/admin/news/list'))

        return self.success(msg='资讯删除成功', url=self.makeUrl('/admin/news/list'))

    def deleteBatch(self):
        inputParams = self.getInput()
        try:
            condition = ' id IN (' + inputParams['delitems'] +')'
            news().delete(condition)
        except Exception, e:
            return self.error(msg='资讯删除失败: %s' % e, url=self.makeUrl('/admin/news/list'))

        return self.success(msg='资讯删除成功', url=self.makeUrl('/admin/news/list'))


    def add(self):
        condition = {}
        categoryList = category().getList('*', condition)

        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        self.privData['IMG_URL_LIST'] = {};
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 
                self.privData['IMG_URL_LIST'][img['id']] = self.imageUrl(img['id'])

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = 1
        self.privData['SUBMIT_NAME'] = "thumbnail"

        return self.display('newsAdd')
    
    def modify(self):
        userInput= self.getInput()

        try: 
            desc =  userInput['desc'] if userInput['desc'] else userInput['content']   
            data={
                'content':      self.htmlunquote(userInput['content']),
                'name':         userInput['name'],
                'desc':         self.subText(self.htmlunquote(desc), 0, 32),
                'status':       userInput['status'],
                'category':     int(userInput['category']),
                'thumbnail':    int(userInput['thumbnail']),
            }

            condition={'id': int(userInput['id'])}
            news().update(data, condition)
        except Exception, e:
            return self.error(msg = '资讯修改失败: %s' % e, url=self.makeUrl('/admin/news/list'))

        return self.success('资讯修改成功', url=self.makeUrl('/admin/news/list'))

    def edit(self):
        inputParams = self.getInput()
        condition={'id': int(inputParams['id'])}
        newsObj = news().getOne('*', condition)
        if not newsObj:
            return self.error(msg = '资讯不存在')
        self.privData['NEWS_INFO'] = newsObj

        condition = {}
        categoryList = category().getList('*', condition)
        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']
        
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        self.privData['IMG_URL_LIST'] = {};
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 
                self.privData['IMG_URL_LIST'][img['id']] = self.imageUrl(img['id'])

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = newsObj['thumbnail']
        self.privData['SUBMIT_NAME'] = "thumbnail"

        return self.display('newsEdit')


    def save(self):
        userInput= self.getInput()
        import time
        currentDate = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())


        try:
            desc = userInput['desc'] if userInput['desc'] else userInput['content']
            data = {
                'content':      self.htmlunquote(userInput['content']),
                'desc':         self.subText(self.htmlunquote(desc), 0, 32),
                'name':         userInput['name'],
                'createTime':   currentDate,
                'status':       int(userInput['status']),
                'category':     int(userInput['category']),
                'thumbnail':    int(userInput['thumbnail']),
            }
            news().insert(data)
        except Exception, e:    
            return self.error(msg = '资讯保存失败: %s' % e, url=self.makeUrl('/admin/news/list'))

        return self.success('资讯保存成功', url=self.makeUrl('/admin/news/list'))
